const BaseRes = require("../module/baseRes");
const User = require("../module/user");
const encryption = require("../utils/md5");
const { insertOne, selectOne } = require("../utils/db");
const jwt = require("../utils/jwt");
const config = require("../config");
exports.register = async (req, res, next) => {
  try {
    let user = req.body;
    // 根据手机号，查询数据是否已被注册
    let sqlByPhone = "select phone from user where phone = ?";
    const isHasUser = await selectOne(sqlByPhone, user.phone);
    if (isHasUser[0][0]) {
      res.status(400).send(new BaseRes(400, false, "该用户已存在"));
      return;
    }
    // 用户密码md5加密后保存
    let md5psd = encryption(user.password);
    let saveUser = new User(user);
    saveUser.password = md5psd;
    // 保存用户信息
    let sql = "insert into user set ?";
    const result = await insertOne(sql, saveUser);
    if (result[0].affectedRows === 1) {
      res.status(200).send(new BaseRes(200, true, "注册成功！"));
    }
  } catch (error) {
    next(error);
  }
};

exports.login = async (req, res, next) => {
  try {
    let user = req.body;
    let selsql = "select * from user where nickname = ?";
    const isHasUser = await selectOne(selsql, user.nickname);
    if (!isHasUser[0][0]) {
      res.status(400).send(new BaseRes(400, false, "用户不存在"));
      return;
    }
    const md5psd = encryption(user.password);
    if (md5psd !== isHasUser[0][0].password) {
      res.status(400).send(new BaseRes(400, false, "用户密码不正确"));
      return;
    }
    // 生成token返回给用户
    const token = await jwt.sign(
      {
        nickname: user.nickname,
      },
      config.jwtSalt,
      { expiresIn: 3600 * 24 * 7 }
    );

    res.status(200).send(new BaseRes(200, true, "登录成功", { token }));
  } catch (error) {
    console.log(error);
  }
};

exports.getUserById = async (req, res, next) => {
  const id = req.params.id;
  if (id) {
    const user = new User();
    console.log(user);
  }

  try {
    res.send("seccuss login");
  } catch (error) {
    console.log(error);
  }
};
